package com.leetcode.sorts.linked;

/**
 * @Author: WuPeng
 * @Date: 2021/5/24 11:48 上午
 *
 * 206.反转链表
 * 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
 *
 * 示例1：
 *      输入：head = [1,2,3,4,5]
 *      输出：[5,4,3,2,1]
 *
 * 示例 2：
 *      输入：head = [1,2]
 *      输出：[2,1]
 *
 * 示例 3：
 *      输入：head = []
 *      输出：[]
 *
 */
public class ReverseLinked_206 {

    public static ListNode reverseList(ListNode head){
        if (head == null || head.next == null){
            return head;
        }
        ListNode slow = null;
        ListNode fast = head;
        while (fast != null){
            if (fast.next == null){
                fast.next = slow;
                break;
            }

            ListNode slow_tmp = fast.next;
            ListNode fast_tmp = fast.next.next;

            fast.next.next = fast;
            fast.next = slow;

            slow = slow_tmp;
            fast = fast_tmp;
        }
        return slow;
    }

    public static void main(String[] args) {
        ListNode head  = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        ListNode node5 = new ListNode(6);

        head.next  = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode res = reverseList(head);

        while (res!= null){
            System.out.printf("%s\t", res.val);
            res = res.next;
        }
    }

}
